package com.czwj.service.impl;

import java.io.File;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import com.czwj.dao.AttachmentMapper;
import com.czwj.dao.AttachmentRelyMapper;
import com.czwj.dao.FinishApplyMapper;
import com.czwj.dao.ProjectItemChildMapper;
import com.czwj.dao.ProjectItemMapper;
import com.czwj.entities.Attachment;
import com.czwj.entities.AttachmentRely;
import com.czwj.entities.FinishApply;
import com.czwj.entities.ProjectItem;
import com.czwj.entities.ProjectItemChild;
import com.czwj.service.FinishApplyService;
import com.czwj.util.CheckFileFormatUtil;

@Service
public class FinishApplyServiceImpl implements FinishApplyService{
	@Resource
	FinishApplyMapper mapper;
	
	@Resource
	ProjectItemMapper itemmapper;
	
	@Resource
	ProjectItemChildMapper childmapper;
	
	@Resource
	AttachmentMapper amapper;
	
	@Resource
	AttachmentRelyMapper relymapper;
	
	@Value("${resources.phypath}")
	private String PhyPath;
	
	@Value("${resources.respath}")
	private String ResPath;
	
	private final String Attachment_Finish_Apply_Path = "竣工申请/";
	
	SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
	
	@Override
	public List<FinishApply> searchbylevel3(Map<String,Object> map){
		// TODO Auto-generated method stub
		return this.mapper.searchbylevel3(map);
	}
	
	@Override
	public int countbylevel3(Map<String,Object> map){
		// TODO Auto-generated method stub
		return this.mapper.countbylevel3(map);
	}
	
	@Override
	public int update(FinishApply finishApply){
		// TODO Auto-generated method stub
		return this.mapper.updateByPrimaryKeySelective(finishApply);
	}
	
	@Override
	public int insert(FinishApply finishApply){
		// TODO Auto-generated method stub
		return this.mapper.insert(finishApply);
	}
	
	@Override
	public int updateStatus(int id){
		// TODO Auto-generated method stub
		return this.mapper.updateStatus(id);
	}
	
	@Override
	public FinishApply selectByPrimaryKey(int id){
		// TODO Auto-generated method stub
		return this.mapper.selectByPrimaryKey(id);
	}
	
	@Override
	public FinishApply searchbyprojectitemid(int id){
		// TODO Auto-generated method stub
		return this.mapper.searchbyprojectitemid(id);
	}
	
	@Override
	public List<FinishApply> searchReviewedLevel1(Map<String,Object> map){
		// TODO Auto-generated method stub
		return this.mapper.searchReviewedLevel1(map);
	}
	
	@Override
	public int countReviewedLevel1(Map<String,Object> map){
		// TODO Auto-generated method stub
		return this.mapper.countReviewedLevel1(map);
	}
	
	@Override
	public List<FinishApply> searchReviewedLevel2(Map<String,Object> map){
		// TODO Auto-generated method stub
		return this.mapper.searchReviewedLevel2(map);
	}
	
	@Override
	public int countReviewedLevel2(Map<String,Object> map){
		// TODO Auto-generated method stub
		return this.mapper.countReviewedLevel2(map);
	}
	
	@Override
	public List<FinishApply> searchbyprojectitem(Integer projectitemid){
		// TODO Auto-generated method stub
		return this.mapper.searchbyprojectitem(projectitemid);
	}
	
	@Transactional
	@Override
	public int insertorupdate(Integer id,Integer projectitemid,String content,Integer status,int createrid,
			String createip,MultipartFile[] images){
		// TODO Auto-generated method stub
		int count = 0;
		if(id == null){
			try{
				FinishApply finishApply = new FinishApply(id,projectitemid,content,status,createrid,new Date(),
						createip);
				count += this.mapper.insertSelective(finishApply);
				ProjectItem item = this.itemmapper.selectByPrimaryKey(projectitemid);
				if(status == 5){
					Map<String,Object> map = new HashMap<String,Object>();
					map.put("id",item.getId());
					map.put("status",status);
					itemmapper.updatestatus(map);
					List<ProjectItemChild> list = childmapper.findbyfather(item.getId());
					for(ProjectItemChild projectItemChild:list){
						Map<String,Object> map2 = new HashMap<String,Object>();
						map2.put("id",projectItemChild.getId());
						map2.put("status",status);
						childmapper.updateStatus(map2);
					}
				}
				String path = item.getName() + "/" + Attachment_Finish_Apply_Path + sdf.format(new Date()) + "/";
				String sourcepath = PhyPath + path;// 存储路径
				String urlpath = ResPath + path;// 资源路径
				File dest = new File(sourcepath);
				if(!dest.exists()){
					dest.mkdirs();
				}
				for(MultipartFile _file:images){
					String filename = _file.getOriginalFilename();
					String _sourcepath = sourcepath + filename;
					String _urlpath = urlpath + filename;
					File file = new File(_sourcepath);
					while(file.exists()){
						String[] arr = _sourcepath.split("\\.");
						_sourcepath = "";
						for(int i = 0;i < arr.length;i++){
							if(i < arr.length - 1){
								_sourcepath += arr[i];;
							}else{
								_sourcepath += "(1)." + arr[i];
							}
						}
						file = new File(_sourcepath);
					}
					_file.transferTo(new File(_sourcepath));
					String suffix = filename.substring(filename.lastIndexOf(".") + 1);
					String type = "";
					if(suffix == null){
						type = "other";
					}else if(suffix.contains("doc")){
						type = "doc";
					}else if(suffix.contains("xls")){
						type = "xls";
					}else if(suffix.contains("ppt")){
						type = "ppt";
					}else{
						type = CheckFileFormatUtil.getFileType(_sourcepath);
					}
					Attachment attachment = new Attachment(filename,_urlpath,_sourcepath,type,createrid,new Date(),
							createip);
					count += this.amapper.insertSelective(attachment);
					AttachmentRely aRely = new AttachmentRely("finishapply",finishApply.getId(),attachment.getId());
					count += this.relymapper.insertSelective(aRely);
				}
			}
			catch(Exception e){
				// TODO Auto-generated catch block
				return 0;
			}
		}else{
			try{
				FinishApply finishApply = new FinishApply(id,projectitemid,content,status,createrid,new Date(),
						createip);
				count += this.mapper.updateByPrimaryKeySelective(finishApply);
				ProjectItem item = this.itemmapper.selectByPrimaryKey(projectitemid);
				if(status == 5){
					Map<String,Object> map = new HashMap<String,Object>();
					map.put("id",item.getId());
					map.put("status",status);
					itemmapper.updatestatus(map);
					List<ProjectItemChild> list = childmapper.findbyfather(item.getId());
					for(ProjectItemChild projectItemChild:list){
						Map<String,Object> map2 = new HashMap<String,Object>();
						map2.put("id",projectItemChild.getId());
						map2.put("status",status);
						childmapper.updateStatus(map2);
					}
				}
				String path = item.getName() + "/" + Attachment_Finish_Apply_Path + sdf.format(new Date()) + "/";
				String sourcepath = PhyPath + path;// 存储路径
				String urlpath = ResPath + path;// 资源路径
				File dest = new File(sourcepath);
				if(!dest.exists()){
					dest.mkdirs();
				}
				for(MultipartFile _file:images){
					String filename = _file.getOriginalFilename();
					String _sourcepath = sourcepath + filename;
					String _urlpath = urlpath + filename;
					File file = new File(_sourcepath);
					while(file.exists()){
						String[] arr = _sourcepath.split("\\.");
						_sourcepath = "";
						for(int i = 0;i < arr.length;i++){
							if(i < arr.length - 1){
								_sourcepath += arr[i];;
							}else{
								_sourcepath += "(1)." + arr[i];
							}
						}
						file = new File(_sourcepath);
					}
					_file.transferTo(new File(_sourcepath));
					String suffix = filename.substring(filename.lastIndexOf(".") + 1);
					String type = "";
					if(suffix == null){
						type = "other";
					}else if(suffix.contains("doc")){
						type = "doc";
					}else if(suffix.contains("xls")){
						type = "xls";
					}else if(suffix.contains("ppt")){
						type = "ppt";
					}else if(suffix.contains("pdf")){
						type = "pdf";
					}else{
						type = CheckFileFormatUtil.getFileType(_sourcepath);
					}
					Attachment attachment = new Attachment(filename,_urlpath,_sourcepath,type,createrid,new Date(),
							createip);
					count += this.amapper.insertSelective(attachment);
					AttachmentRely aRely = new AttachmentRely("finishapply",finishApply.getId(),attachment.getId());
					count += this.relymapper.insertSelective(aRely);
				}
			}
			catch(Exception e){
				// TODO Auto-generated catch block
				return 0;
			}
		}
		return count;
	}
	
	@Transactional
	@Override
	public int remove(int id){
		// TODO Auto-generated method stub
		int count = 0;
		FinishApply finishApply = this.mapper.selectByPrimaryKey(id);
		count += this.mapper.deleteByPrimaryKey(id);
		for(Attachment attachment:finishApply.getAttachments()){
			File file = new File(attachment.getPath());
			if(file.exists()){
				file.delete();
			}
			count += this.amapper.deleteByPrimaryKey(attachment.getId());
			count += this.relymapper.deleteByAttachmentid(attachment.getId());
		}
		return count;
	}
}
